'use strict';
const db = uniCloud.database();
const FormData = require("form-data");
exports.main = async (event) => {
	let {
		data = {}, userInfo, util, originalParam
	} = event;
	let {
		customUtil,
		config,
		pubFun,
		vk,
		db,
		_
	} = util;
	let {
		uid,
		img
	} = data;
	let res = {
		code: 0,
		msg: ''
	};
	//event为客户端上传的参数
	let appIds = await db.collection('wx_config').where({
		'key': 'AK'
	}).get()
	let appSecrets = await db.collection('wx_config').where({
		'key': 'SK'
	}).get()
	if (appIds.data.length === 0 || appSecrets.data.length === 0) {
		return '百度key和秘钥未配置'
	}
	const AK = appIds.data[0].val
	const SK = appSecrets.data[0].val
	/**
	 * 使用 AK，SK 生成鉴权签名（Access Token）
	 */
	var url =
		`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`
	const accessToken = await uniCloud.httpclient.request(url, {
		method: "POST",
		contentType: 'json',
		dataType: "json"
	})
	var access_token = accessToken.data.access_token
	if (!access_token) {
		res.msg = '百度key和秘钥错误';
		res.code = -1
		return res
	}
	var url = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${access_token}`
	const imgUrl = await uniCloud.httpclient.request(img)
	let form = new FormData()
	let buff = new Buffer(imgUrl.data);
	form.append('url', img)
	const imgData = await uniCloud.httpclient.request(url, {
		method: "POST",
		headers: form.getHeaders(),
		dataType: 'json',
		content: form.getBuffer()
	})

	console.log(imgData,'12121111111111')
	res.data = imgData.data.words_result
	return res



};
